import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' hide FormData;
import 'package:getx_app/app/constant/api.dart';
import 'package:getx_app/app/routes/app_pages.dart';
import 'package:sp_util/sp_util.dart';

class LoginController extends GetxController {
  final Dio dio = Get.find<Dio>();

  final formKey = GlobalKey<FormState>();

  bool isLoading = false;

  bool obscureTextPassword = true;

  String? account;
  String? pwd;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  doLogin() async {
    FormState form = formKey.currentState!;
    form.save();
    isLoading = true;
    update();
    if (!form.validate()) {
      Fluttertoast.showToast(msg: "登录失败", gravity: ToastGravity.CENTER).then((value) {
        isLoading = false;
        update();
      });
    } else {
      var formData = FormData.fromMap({
        'shop_id': ApiConstant.SHOP_ID,
        'username': account,
        'password': pwd,
      });
      final rs = await dio.post("/h5/auth/login_by_pwd", data: formData);
      Map data = rs.data;
      SpUtil.putString("token", data['access_token']);
      SpUtil.putBool("isLogin", true);
      isLoading = false;
      update();
      Get.offNamed(Routes.HOME);
    }
  }

  @override
  void onClose() {}

  void toggleObscureText() {
    obscureTextPassword = !obscureTextPassword;
    update();
  }
}
